package com.tdam2011.grupo06.gui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.Iterator;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tdam2011.grupo06.R;
import com.tdam2011.grupo06.control.DatabaseHelper;
import com.tdam2011.grupo06.control.GestorContactos;
import com.tdam2011.grupo06.gui.PullToRefreshListView.OnRefreshListener;
import com.tdam2011.grupo06.model.*;

public class ListadoContactos extends ListActivity implements OnItemClickListener 
{
	private LinearLayout linearLay;
	private ContactAdapter adapter;
	private CargarContactosTask cargarContactosTask;
	private GestorContactos gestorContacto;
	private int idContacto;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lista_contactos);
		adapter = new ContactAdapter();
		gestorContacto = new GestorContactos(this);
		gestorContacto.actualizar();
		linearLay = (LinearLayout) findViewById(R.id.linearLayoutListaContactos);
		setListAdapter(adapter);

		getListView().setOnItemClickListener(this);
		registerForContextMenu(getListView());
		
		// Set a listener to be invoked when the list should be refreshed.
		((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
		    @Override
		    public void onRefresh() {
		    	if(cargarContactosTask!=null){
		    		cargarContactosTask.cancel(true);
		    	}
		    	cargarContactosTask = new CargarContactosTask();
		    	cargarContactosTask.execute("");
		    }
		});
		((PullToRefreshListView) getListView()).onRefresh();
	}
	
	public class ContactAdapter extends BaseAdapter 
	{
		private ArrayList<Contacto> contacts;
		private LayoutInflater inflater;

		public ContactAdapter() 
		{
			contacts = new ArrayList<Contacto>();
			inflater = LayoutInflater.from(ListadoContactos.this);
		}

		public void addContactInfo(Contacto info) {
			if (info != null) {
				contacts.add(info);
			}
		}

		public int getCount() {
			return contacts.size();
		}

		public Object getItem(int position) {
			return contacts.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public Contacto getItemById(int id) 
		{
			Iterator<Contacto> iter = contacts.iterator();
			Contacto aux;
			while (iter.hasNext())
			{
				aux = iter.next();
				if(aux.getDbId()==id)
				{
					return aux; 
				}
			}
			return null;
		}

		public void emptyLists()
		{
			contacts.clear();
		}
		
		public void ordenarContactos(Comparator<Contacto> c)
		{
			Collections.sort(contacts, c);
		}
		
		class Holder 
		{
			private TextView txtNombre;
			private ImageView imgContacto;
			private TextView txtTel;
		}

		public View getView(int position, View convertView, ViewGroup arg2) 
		{
			Holder holder;
			if (convertView == null) 
			{
				convertView = inflater.inflate(R.layout.item_contacto, null);
				holder = new Holder();
				holder.imgContacto = (ImageView) convertView.findViewById(R.id.imageViewContactoImagen);
				holder.txtNombre = (TextView) convertView.findViewById(R.id.txtContactNombre);
				holder.txtTel = (TextView) convertView.findViewById(R.id.txtContactoTel);
				convertView.setTag(holder);
			} 
			else 
			{
				holder = (Holder) convertView.getTag();
			}

			Contacto info = (Contacto) getItem(position);
			holder.txtNombre.setText(info.getNombre());
			holder.txtTel.setText(info.getNumPre());
			holder.imgContacto.setImageURI( info.getPhotoUri() );
			return convertView;
		}

	}
	
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) 
	{
		Contacto c = (Contacto) adapter.getItem(position -1);
		Intent intent = new Intent(this,PresentacionContacto.class);
		intent.putExtra("idContacto", c.getDbId());
		startActivity(intent);
	}
	
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) 
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		
		Contacto c = (Contacto) adapter.getItem(((AdapterView.AdapterContextMenuInfo)menuInfo).position-1);
		
		menu.setHeaderTitle("Acciones de contacto");
		if(c.getTel().size()!=0)
		{
			SubMenu sML = menu.addSubMenu(0, v.getId(), 0, "Llamar");
			SubMenu sMM = menu.addSubMenu(0, v.getId(), 0, "Enviar mensaje de texto");
			for(int i = 0; i < c.getTel().size(); i++)
			{
				sML.add(0, v.getId(), 1, c.getTel(i).getNumero());
				sMM.add(0, v.getId(), 2, c.getTel(i).getNumero());
			}
		}
		menu.add(0, c.getDbId(), 4, "Enviar mensaje web");
		
		ContentResolver cr = getContentResolver();
		Cursor eCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID +" = ?",new String[]{String.valueOf(c.getDbId())}, null);
		c.clearEmail();
    	while (eCur.moveToNext()) 
        {
			String idMail = eCur.getString(eCur.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
			String m = eCur.getString(eCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
			String type = eCur.getString(eCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
			c.addEmail(new Email(Integer.parseInt(idMail), m, Integer.parseInt(type)));		        		
        } 
        eCur.close();
	        
		if(c.getEmail().size()!=0)
		{
			SubMenu sME = menu.addSubMenu(0, v.getId(), 0, "Enviar mail");
			for(int i = 0; i < c.getEmail().size(); i++)
			{
				sME.add(0, c.getDbId(), 3, c.getEmail(i).getMail());
			}
		}
		menu.add(0, c.getDbId(), 5, "Ver historial");
		if(c.getTel().size()!=0)
		{
			SubMenu sMP = menu.addSubMenu(0, v.getId(), 6, "Setear predeterminado");
			DatabaseHelper db = DatabaseHelper.getInstance(this);
			c = db.getContactByDBId(c);
			for(int i = 0; i < c.getTel().size(); i++)
			{
				sMP.add(c.getDbId(), c.getTel(i).getId(), 6, c.getTel(i).getNumero());
				if(c.getTelPref()==c.getTel(i).getId())
				{
					sMP.getItem(i).setChecked(true);
				}
			}
			sMP.setGroupCheckable(c.getDbId(), true, true);
		}
	}
	
	public boolean onContextItemSelected(MenuItem item) 
	{
		String url;
		Intent intent;
		Contacto c;
		DatabaseHelper db;

		switch(item.getOrder())
		{
			case 1:
				url = "tel:"+item.getTitle();
				intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
				startActivity(intent);				
				return true;
			case 2:
				url = "smsto:"+item.getTitle();
				intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
				intent.putExtra("compose_mode", true);
		        startActivity(intent);
				return true;
			case 3:
				c = (Contacto) adapter.getItemById(item.getItemId());
				db = DatabaseHelper.getInstance(this);
				if(c.getTableID()==0){
					c = db.getContactByDBId(c);
				}				
				ItemEmail ie = new ItemEmail(0, c.getTableID(), 2, GregorianCalendar.getInstance().getTime(), (String) item.getTitle(), c.getNombre());
				if(!db.existsContactByDBId(c))
				{
					db.addContacts(c);
				}
				db.addEmail(ie);
				intent = new Intent(Intent.ACTION_SEND); 
				intent.setType("plain/text");
				intent.putExtra(Intent.EXTRA_EMAIL, new String[]{(String) item.getTitle()}); 
				startActivity(Intent.createChooser(intent, getResources().getString(R.string.selec_ap_mail)));
				return true;
			case 4:
				c = (Contacto) adapter.getItemById(item.getItemId());
				db = DatabaseHelper.getInstance(this);
				idContacto = c.getDbId();
				c = db.getContactByDBId(c);
				if(!db.existsContactByDBId(c))
				{
					showDialog(2);
				}
				else
				{
					c = db.getContactByDBId(c);
					if(c.getUsuario()==null)
					{
						showDialog(2);
					}
					else
					{
						startActivity(new Intent(this, ListadoMensajesBob.class).putExtra("nombreUsuario", c.getUsuario()).putExtra("idContacto", c.getTableID()));
					}
				}
				return true;
			case 5:
				c = (Contacto) adapter.getItemById(item.getItemId());
				intent = new Intent(this,HistorialContacto.class);
				intent.putExtra("idContacto", c.getDbId());
				startActivity(intent);
				return true;
			case 6:
				if(item.getGroupId()!=0)
				{
					c = (Contacto) adapter.getItemById(item.getGroupId());
					db = DatabaseHelper.getInstance(this);
					c.setTelPref(item.getItemId());
					if(!db.existsContactByDBId(c))
					{
						db.addContacts(c);
					}
					else
					{
						db.updatePrefTelByDBId(c);
					}
					c.setNumPre(c.getTelById(c.getTelPref()).getNumero());
					adapter.notifyDataSetChanged();
				}
				return true;
			default:
				return super.onContextItemSelected(item);
		}
    }
	
	protected void onResume() 
	{
		super.onResume();
	}
	
	@Override
	protected void onPause() 
	{
		super.onPause();
	}

	@Override
	protected void onStop() 
	{
		super.onStop();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    menu.add(Menu.NONE, 1, Menu.NONE, "Preferencias");
	    menu.add(Menu.NONE, 2, Menu.NONE, "Filtrar por");
	    SubMenu smnuOrd = menu.addSubMenu(Menu.NONE, Menu.NONE, Menu.NONE, "Ordenar por");
	    smnuOrd.add(Menu.NONE, 3, 1, "Nombre ascendente");
	    smnuOrd.add(Menu.NONE, 3, 2, "Nombre descendente");
	    smnuOrd.add(Menu.NONE, 3, 3, "Tel predet ascendente");
	    smnuOrd.add(Menu.NONE, 3, 4, "Tel predet descendente");
	    smnuOrd.setGroupCheckable(Menu.NONE, true, true);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    switch (item.getItemId()) 
	    {
	        case 1:
	        	startActivity(new Intent(this, SetPreferenceNombreUsuario.class).putExtra("NoInicio", true));
	            return true;
	        case 2:
	        	startActivityForResult(new Intent(this, SetPreferenceFiltrarContactos.class),0);
	            return true;
	        case 3:
	        	SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
	        	SharedPreferences.Editor editor = myPreference.edit();
	        	String[] order = getResources().getStringArray(R.array.ordenamietoContactos);
	        	switch (item.getOrder()) 
	    	    {
	    	        case 1:
	    	        	editor.putString("ordenamietoContactos", order[0]);
	    	        	adapter.ordenarContactos(Contacto.comparadorNombreAsc);
	    	            break;
	    	        case 2:
	    	        	editor.putString("ordenamietoContactos", order[1]);
	    	        	adapter.ordenarContactos(Contacto.comparadorNombreDesc);
	    	            break;
	    	        case 3:
	    	        	editor.putString("ordenamietoContactos", order[2]);
	    	        	adapter.ordenarContactos(Contacto.comparadorTelPreAsc);
	    	            break;
	    	        case 4:
	    	        	editor.putString("ordenamietoContactos", order[3]);
	    	        	adapter.ordenarContactos(Contacto.comparadorTelPreDesc);
	    	            break;
	    	    }
	        	adapter.notifyDataSetChanged();
	            return editor.commit();
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		SubMenu smnuOrd = menu.getItem(2).getSubMenu();
		SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
    	String[] order = getResources().getStringArray(R.array.ordenamietoContactos);
    	String orden = myPreference.getString("ordenamietoContactos", "");
    	for (int i = 0; i<order.length; i++)
    	{
    		if(order[i].compareTo(orden)==0)
    		{
    			smnuOrd.getItem(i).setChecked(true);
    		}
    	}
	    return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 0) 
		{
			if (data!=null)
			{
				gestorContacto.actualizar();
				((PullToRefreshListView) getListView()).onRefresh();
			}
		}
	}
	private class CargarContactosTask extends AsyncTask<String, Void, ContactAdapter>{
	    
	    protected void onPostExecute(ContactAdapter result) {
	    	if(result!=null)
			{
				adapter = result;
				adapter.notifyDataSetChanged();
			}
	    	
	    	if(linearLay.getVisibility()!=View.GONE){
	    		linearLay.setVisibility(View.GONE);
	    	}
	    	if(adapter.isEmpty()){
    			((PullToRefreshListView) getListView()).onRefreshComplete(getResources().getString(R.string.empty_listContactos));
    		}
    		else{
    			((PullToRefreshListView) getListView()).onRefreshComplete(null);
    		}
	        
	        super.onPostExecute(result);
	    }

		@Override
		protected ContactAdapter doInBackground(String... params) {
			boolean flag = gestorContacto.verificarContactos(adapter);
			
			if(flag)
			{
				adapter.emptyLists();
				return gestorContacto.cargarContactos(adapter);
			}
			return null;
		}
	}
	
	protected Dialog onCreateDialog(int id) 
	{
		Dialog dialog = null;
		if (id ==1) 
		{
			dialog = new AlertDialog.Builder(this).setIcon(R.drawable.ic_alert).setPositiveButton("Ok", null).setMessage("Todavia no se ha cargado los contactos").setTitle("Error").create();
		}
		else if (id == 2)
		{
			dialog = createCustomDialog();
		}
		else 
		{
			dialog = super.onCreateDialog(id);
		}
		return dialog;
	}
	
	@Override
	public void onBackPressed() 
	{
		super.onBackPressed();
	}
	
	private Dialog createCustomDialog() {
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.custom_dialog);
		dialog.setTitle(getResources().getString(R.string.tituloDialogo));

		final EditText textUsuario = (EditText) dialog.findViewById(R.id.dialogTxtNombre);
		Button btnAceptar = (Button) dialog.findViewById(R.id.dialogBtnAceptar);
		Button btnCancelar = (Button) dialog.findViewById(R.id.dialogBtnCancelar);
		
		btnAceptar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) 
			{
				Contacto c = new Contacto(idContacto);
				c.setUsuario(textUsuario.getText().toString());
				DatabaseHelper db = DatabaseHelper.getInstance(ListadoContactos.this);
				if(!db.existsContactByDBId(c))
				{
					db.addContacts(c);
				}
				else
				{
					db.updateUserByDBId(c);
				}
				c = db.getContactByDBId(c);
				startActivity(new Intent(ListadoContactos.this, ListadoMensajesBob.class).putExtra("nombreUsuario", c.getUsuario()).putExtra("idContacto", c.getTableID()));
				dialog.dismiss();
			}
		});
		
		btnCancelar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		return dialog;
	}
}
